package com.itboye.boyeshoping.ViewUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.itboye.boyeshoping.R;
import com.itboye.boyeshoping.inf.OnItemClickListenner;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/6/29 0029.
 */

public class HorzontalScrollTable extends LinearLayout {

    private OnItemClickListenner listenner;

    private boolean isAdapterText;// ture 滑块自适应table内容   false滑块不用自适应
    private boolean isSameWidth;//table 是否等宽
    private Context context;

    private LinearLayout scrollRv;
    private ImageView scrollLine;
    private RelativeLayout scrollTable;




    private int sliderHigh;
    private int tablePading;

    private int fen;//table  满屏显示几块



    private int wWidth,wHigh;//屏幕宽高

    private int currIndex;//当前的index
    private int currindexWidth;//
    private int scrollIndex;//要滑动的位置


    //item Textview 的宽度即滑块应该变化的宽度
    private int scaleWidth;
    //上一次的滑块的宽度
    private int oldScaleWidth;

    private int animalTime;

    MyRecleAdapter myRecleAdapter;

    private int scroll_Width;


    public HorzontalScrollTable(Context context) {
        this(context,null);
    }

    public HorzontalScrollTable(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);


    }

    public HorzontalScrollTable(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initCustomAttrs(context,attrs);
        initView();
    }

    private void initCustomAttrs(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.HorzontalScrollTable);
//        app:table_padingRL="20dip"
//        app:tableNum="5"
//        app:scroll_slider="2dip"
        isAdapterText = typedArray.getBoolean(R.styleable.HorzontalScrollTable_adapter_text, false);
        isSameWidth = typedArray.getBoolean(R.styleable.HorzontalScrollTable_sameWidth, false);
        fen=typedArray.getInteger(R.styleable.HorzontalScrollTable_tableNum,5);
        animalTime = typedArray.getInteger(R.styleable.HorzontalScrollTable_animal_time, 500);
        tablePading =  typedArray.getDimensionPixelSize(R.styleable.HorzontalScrollTable_table_padingRL, 20);
        sliderHigh = typedArray.getDimensionPixelSize(R.styleable.HorzontalScrollTable_scroll_slider, 2);

    }


//    /**
//     *
//     * @param context
//     * @param type  1 滑块自适应table内容   2 滑块不用自适应
//     * @param list  table数组
//     * @param lineHigh  滑块距离table底部的高度
//     * @param high  item 高度
//     * @param tableColor  item Textcolor
//     * @param fen  table 满屏显示几个
//     */
//    public HorzontalScrollTable(Context context, int type, List<String> list, int lineHigh, int high,int tableColor,int fen,int pxWidth){
//        super(context);
//        this.type=type;
//        this.context=context;
//        this.list=list;
//        this.lineHigh=lineHigh;
//        this.high=high;
//        this.tableColor=tableColor;
//        this.fen=fen;
//        this.wWidth=pxWidth;
//        initView();
//    }

    public void setListData(final List<String> list, Context context, int wWidth){
         this.context=context;
         this.wWidth=wWidth;
         for (int i=0;i<list.size();i++){
             TextView textView = new TextView(context);
             LinearLayout.LayoutParams params;
             if (isSameWidth){
                 params=new LinearLayout.LayoutParams(wWidth/fen, LayoutParams.MATCH_PARENT);
             }else {
                 params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
                 params.setMargins(tablePading,0,0,0);
             }
             textView.setLayoutParams(params);
             textView.setGravity(Gravity.CENTER);
             textView.setText(list.get(i));
             scrollRv.addView(textView);


             final int finalI = i;
             textView.setOnClickListener(new OnClickListener() {
                 @Override
                 public void onClick(View view) {
//                     tranSlateAndScale(currindexWidth,scrollIndex,oldScaleWidth,scaleWidth,animalTime);
                     tranSlateAndScale(currindexWidth,getScrollIndext(finalI,list),0,0,500);

                 }
             });
         }

        //计算的textview 的宽

            int text = getTextWidth(list.get(0), context);
            RelativeLayout.LayoutParams params1 =new RelativeLayout.LayoutParams(text, sliderHigh);
            params1.setMargins((wWidth/fen-text)/2,0,0,8);
            params1.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.scrollTable);
            scrollLine.setLayoutParams(params1);
            currindexWidth=(wWidth/fen-text)/2;



    }

    public int getScrollIndext(int i,List<String> list){
        return  wWidth/fen*i+(wWidth/fen-getTextWidth(list.get(i),context))/2;
    }

    public int getTextWidth(String str,Context context){
        final TextView textView = new TextView(context);
        LinearLayout.LayoutParams params =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(params);
        textView.setTextSize(14);
        textView.setText(str);
        int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(spec,spec);
        int measuredWidth = textView.getMeasuredWidth();
        return measuredWidth;
    }

    @SuppressLint("NewApi")
    private void initView() {

        LayoutInflater from = LayoutInflater.from(getContext());
        View contentView = from.inflate(R.layout.horzontalscrolltable, this);
//        View contentView = LayoutInflater.from(context).inflate(R.layout.horzontalscrolltable,null,false);

        scrollTable= (RelativeLayout) contentView.findViewById(R.id.scrollTable);
        scrollLine= (ImageView) contentView.findViewById(R.id.scrollLine);
        scrollRv= (LinearLayout) contentView.findViewById(R.id.scrollRv);
        scrollLine.setBackgroundColor(getResources().getColor(R.color.white));


    }

    class  MyRecleAdapter extends RecyclerView.Adapter<MyRecleAdapter.MyViewHolder>{
        private List<String> list;//table数组
        public MyRecleAdapter(List<String> list){
            this.list=list;
        }
        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.item_scrollhorzontaltable, null));

            return myViewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
            holder.setIsRecyclable(false);
            if (list.size()>0){
                holder.content.setText(list.get(position));
                holder.content.setTextColor(getResources().getColor(R.color.white));
                if (position==0){
                    ViewTreeObserver vto2=holder.content.getViewTreeObserver();
                    vto2.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                        @Override
                        public boolean onPreDraw() {
                            oldScaleWidth = holder.content.getMeasuredWidth();
                            RelativeLayout.LayoutParams params =new RelativeLayout.LayoutParams(oldScaleWidth, sliderHigh);
                            params.topMargin=holder.content.getBottom()+6;
                            if (isAdapterText){
                                if (isSameWidth){
                                    params.leftMargin=holder.content.getLeft();

                                }else {
                                    params.leftMargin=tablePading;
                                }
                            }
                            currIndex=params.leftMargin;
                            scrollLine.setLayoutParams(params);
                            return true;
                        }
                    });

                }

                LinearLayout.LayoutParams params;
                if (isSameWidth){
                    params=new LinearLayout.LayoutParams(wWidth/fen, LayoutParams.MATCH_PARENT);
                }else {
                    params=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
                    params.setMargins(tablePading,0,0,0);
                }

                holder.ItemLl.setLayoutParams(params);
                holder.ItemLl.setGravity(Gravity.CENTER);
                currindexWidth=currIndex;
                holder.content.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {

//                    scaleWidth=scrollRv.getChildAt(position).getWidth();

                    scrollIndex=scrollRv.getChildAt(position).getLeft();
                        TextView viewById = (TextView) scrollRv.getChildAt(position).findViewById(R.id.contentTV);
                         scaleWidth = viewById.getMeasuredWidth();
                        tranSlateAndScale(currindexWidth,scrollIndex,oldScaleWidth,scaleWidth,animalTime);
//                        scale(scrollIndex,oldScaleWidth,scaleWidth,animalTime,scrollLine.getTop());
//                        tranSlate(currindexWidth,scrollIndex,animalTime);
                        //scrollIndex x 左侧坐标

                        Log.d("=========",scaleWidth+"");
                        listenner.onItemClick(position);

                    }
                });
            }


        }

        @Override
        public int getItemCount() {
            return list.size();
        }


        class MyViewHolder extends RecyclerView.ViewHolder {
            private View itemView;
            private TextView content;
            private LinearLayout ItemLl;//item
            public MyViewHolder(View itemView) {
                super(itemView);
              this.itemView=itemView;
              this.content= (TextView) itemView.findViewById(R.id.contentTV);
              this.ItemLl= (LinearLayout) itemView.findViewById(R.id.ItemLl);
            }
        }

        public void setData(List<String> list1){
            list=list1;
            this.notifyDataSetChanged();
        }

    }


    /**
     * 平移缩放动画
     *
     * @param left
     * @param right
     */
    public void tranSlateAndScale(int left, int right,int oldWidth,int newWidth,int durationMillis) {
//        float one = offset;
//        Log.v("offest", "" + offset);

//        RelativeLayout.LayoutParams params =new RelativeLayout.LayoutParams(oldScaleWidth, sliderHigh);
//        params.leftMargin=right;
//        scrollLine.setLayoutParams(params);

        AnimationSet animationSet = new AnimationSet(true);
        Animation animation = new TranslateAnimation(left,
                right ,0, 0);// 平移动画

        Log.v("currentoffest", "" + left+"==="+right);

//        animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
        animation.setDuration(durationMillis);// 动画持续时间0.2秒
        ScaleAnimation animation1 = new ScaleAnimation(
                1,1, 1, 1);
//        new ScaleAnimation(0,0.1f,0,0.1f,Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);

        animation1.setDuration(durationMillis);// 动画持续时间0.2秒
        animationSet.addAnimation(animation);
//        animationSet.addAnimation(animation1);
        animationSet.setFillAfter(true);
        scrollLine.startAnimation(animationSet);// 是用ImageView来显示动画的
        currindexWidth=right;
//        scrollLine.clearAnimation();
//        RelativeLayout.LayoutParams params =new RelativeLayout.LayoutParams(newWidth, sliderHigh);
//        params.setMargins(right,0,0,0);
//        scrollLine.setLayoutParams(params);
    }

    /**
     * 缩放动画
     *
     * @param oldWidth
     * @param newWidth
     */
    public void scale(int left,int oldWidth,int newWidth  ,int durationMillis,int y) {
//        float one = offset;
//        Log.v("offest", "" + offset);
//        Animation animation = new ScaleAnimation(oldWidth,
//                newWidth, 0, 0);// 平移动画


//        scrollLine.startAnimation(animation);// 是用ImageView来显示动画的
    }

    public  void setOnItemClickListenner(OnItemClickListenner listenner){
        this.listenner=listenner;
    }

}


